#include "stdafx.h"
#include "CfgMgr.h"
#include "Config.h"

using namespace pb::cfg;

CfgMgr::CfgMgr()
{
}

CfgMgr::~CfgMgr()
{
    for (CfgSet::iterator it = m_cfgSet.begin();
         it != m_cfgSet.end(); ++it)
    {
        it->second->save();
           
        delete it->second;
        it->second = 0;
    }

    m_cfgSet.clear();
}

CfgMgr*
CfgMgr::get()
{
    static CfgMgr theInstance;
    return &theInstance;
}

Config*
CfgMgr::loadCfg(const std::wstring& filePath)
{
    if (!filePath.empty())
    {
        Config* cfg = 0;

        CfgSet::iterator it = m_cfgSet.find(filePath);
        if (it == m_cfgSet.end())
        {
            cfg = new Config(filePath);
            m_cfgSet[filePath] = cfg;
        }
        else
        {
            cfg = it->second;
        }

        if (!cfg->load())
        {
            delete cfg;
            cfg = 0;

            m_cfgSet.erase(m_cfgSet.find(filePath));
            return 0;
        }

        return cfg;
    }
    return 0;
}

void 
CfgMgr::saveCfg(Config* cfg)
{
    if (!cfg)
        return;

    cfg->save();
}

void
CfgMgr::unloadCfg(Config*& cfg)
{
    if (!cfg)
        return;

    CfgSet::iterator it = m_cfgSet.find(cfg->filePath());
    if (it != m_cfgSet.end()) 
    {
        if (cfg == it->second) 
        {
            delete it->second;
            it->second = cfg = 0;

            m_cfgSet.erase(it);
        }
        else
            assert(false);
    }
}

Config*
CfgMgr::newCfg(const std::wstring& filePath)
{
    // Check if existed already. If yes, delete it.
    //
    CfgSet::iterator it = m_cfgSet.find(filePath);
    if (it != m_cfgSet.end())
    {
        delete it->second;
        it->second = 0;

        m_cfgSet.erase(it);
    }

    // Create a new Config.
    //
    Config* cfg = new Config(filePath);
    m_cfgSet[filePath] = cfg;

    cfg->m_loaded = true;
    cfg->m_dirty  = true;
    cfg->save();

    return cfg;
}